package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.cache.redis.RedisCache;
import com.mingqijia.gassafety.db.entity.Department;
import com.mingqijia.gassafety.db.entity.DeviceState;
import com.mingqijia.gassafety.db.hangzhou.entity.AlertRecordSign;
import com.mingqijia.gassafety.db.mapper.AlertRecordSignMapper;
import com.mingqijia.gassafety.db.mapper.DepartmentMapper;
import com.mingqijia.gassafety.db.mapper.DeviceStateMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.shared.enums.DealtType;
import com.mingqijia.gassafety.shared.utils.CoordinateTransformer;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.DeviceRequest;
import com.mingqijia.gassafety.webserver.request.HandleRequest;
import com.mingqijia.gassafety.webserver.request.RecordLogRequest;
import com.mingqijia.gassafety.webserver.response.AlertLogResponse;
import com.mingqijia.gassafety.webserver.service.HistoryAlarmService;
import com.mingqijia.gassafety.webserver.service.IRSReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.validation.Valid;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName IRSReportService.java
 * @Description TODO
 * @createTime 2022年12月03日
 */
@Service
@Slf4j
public class IRSReportServiceImpl implements IRSReportService {
    private final Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    RedisCache redisCache;
    @Autowired
    private DtuMapper dtuMapper;
    @Autowired
    private DeviceStateMapper deviceStateMapper;
    @Autowired
    private AlertLogServiceImpl alertLogService;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private AlertRecordSignMapper alertRecordSignMapper;
    @Autowired
    private HistoryAlarmService historyAlarmService;

    @Value(value = "${gassafety.hangzhou.yhSpId}")
    public String yhSpId;

    @Value(value = "${gassafety.hangzhou.lpSpId}")
    public String lpSpId;

    private final String YHSPID_HANGZHOU = "7b3e6340fe3e6e44a5ff7cff7a7bb648";
    private final String LPSPID_HANGZHOU = "DCD598DDEF104C6EA1C4A79B261F1238";

    /**
     * 设备查询
     */
    @Override
    public List<Map<String, Object>> device(@Valid DeviceRequest request) {
        log.info("device-入参：{}", JSONObject.toJSONString(request));
        if (YHSPID_HANGZHOU.equals(request.getSpId())) request.setSpId(yhSpId);
        if (LPSPID_HANGZHOU.equals(request.getSpId())) request.setSpId(lpSpId);
        List<Map<String, Object>> maps = new ArrayList<>();
        maps = dtuMapper.
                selectDtuList(request.getStartTime(), request.getEndTime(), request.getImei(), request.getSpId());

        log.info("device-sql：{}", JSONObject.toJSONString(maps));
        if (!CollectionUtil.isEmpty(maps)) {
            maps.forEach(s -> {
                boolean res = false;
                double[] doubles = new double[2];
                if (s.get("longitude") != null && s.get("latitude") != null) {
                    doubles = CoordinateTransformer.transformBD09ToWGS84(
                            Double.parseDouble(s.get("longitude") + ""), Double.parseDouble(s.get("latitude") + ""));
                }

                if (doubles != null && doubles.length == 2) {
                    s.put("longitude", doubles[0]);
                    s.put("latitude", doubles[1]);
                }
                if ("Gas_alarm_controller".equals(s.get("type") + "")) res = true;
                int status = getStatus(s.get("deviceId") + "", request.getSpId(), res);
                if (status == 0) {
                    s.put("status", "离线");
                } else if (status == 1) {
                    s.put("status", "正常");
                } else if (status == 4) {
                    s.put("status", "故障");
                }else {
                    s.put("status", "报警");
                }
                s.put("address", s.get("address"));
                Object updateTime1 = s.get("updateTime");
                s.put("updateTime", format.format(updateTime1));
                s.remove("Path");
                s.remove("type");
            });
        }
        log.info("device-响应：{}", JSONObject.toJSONString(maps));
        return maps;
    }


    /**
     * 事件查询
     */
    @Override
    public List<Map<String, Object>> event(@Valid DeviceRequest request) {
        log.info("event-入参：{}", JSONObject.toJSONString(request));
        if (YHSPID_HANGZHOU.equals(request.getSpId())) request.setSpId(yhSpId);
        if (LPSPID_HANGZHOU.equals(request.getSpId())) request.setSpId(lpSpId);
        List<Map<String, Object>> maps = new ArrayList<>();
        List<AlertLogResponse> alertLogResponses = new ArrayList<>();
        QueryWrapper<Department> queryWrapper1 = new QueryWrapper<>();
        List<Department> departments = departmentMapper.selectList(queryWrapper1);
        List<AlertLogResponse> list = new ArrayList<>();
        if (!CollectionUtil.isEmpty(departments)) {
            for (Department department : departments) {
                if (!request.getSpId().equals(department.getSpId())) continue;
                int count = 0;
                list = getAlertLogResponsePageUtil(request, count, alertLogResponses, department.getSpId());
            }
        }
        log.info("event-sql：{}", JSONObject.toJSONString(alertLogResponses));
        if (!CollectionUtil.isEmpty(alertLogResponses)) {
            list.forEach(alertLogResponse -> {
                QueryWrapper<AlertRecordSign> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().or().likeRight(AlertRecordSign::getIMEI, alertLogResponse.getImei())

                        .eq(AlertRecordSign::getIsDeleted, 0)
                        .eq(AlertRecordSign::getAlertTime, alertLogResponse.getTime());
                List<AlertRecordSign> alertRecordSigns = alertRecordSignMapper.selectList(queryWrapper);
                String statusMark = "未处理";
                if (!CollectionUtil.isEmpty(alertRecordSigns)) {
                    List<AlertRecordSign> collect = alertRecordSigns.stream().filter(alertRecordSign -> {
                        return 1 == alertRecordSign.getIsFinished();
                    }).collect(Collectors.toList());
                    if (CollectionUtil.isEmpty(collect)) {
                        statusMark = "处理中";
                    } else {
                        statusMark = "已办结";
                    }
                }
                Map<String, Object> map = new HashMap<>();
                map.put("eventId", alertLogResponse.getTime());
                map.put("eventDesc", alertLogResponse.getXlel());
                map.put("deviceId", alertLogResponse.getImei());
                map.put("eventStatus", statusMark);
                map.put("eventTime", format.format(alertLogResponse.getLatestTime()));
                maps.add(map);
            });
        }
        log.info("event-响应：{}", JSONObject.toJSONString(maps));
        return maps;
    }

    /**
     * 处置查询
     *
     * @param request
     * @return
     */
    @Override
    public List<Map<String, Object>> handle(HandleRequest request) {
        log.info("handle-入参：{}", JSONObject.toJSONString(request));
        if (YHSPID_HANGZHOU.equals(request.getSpId())) request.setSpId(yhSpId);
        if (LPSPID_HANGZHOU.equals(request.getSpId())) request.setSpId(lpSpId);
        List<Map<String, Object>> maps = new ArrayList<>();
        if (StringUtils.isEmpty(request.getEventId())) request.setEventId(null);
        List<AlertRecordSign> list = alertRecordSignMapper.
                selectListByTime(request.getImei(), request.getEndTime(), request.getStartTime(), request.getEventId()
                        , request.getSpId());
        log.info("handle-sql：{}", JSONObject.toJSONString(list));
        if (!CollectionUtil.isEmpty(list)) {
            list.forEach(alertRecordSign -> {
                Map<String, Object> map = new HashMap<>();
                map.put("iMEI", alertRecordSign.getIMEI());
                map.put("handleId", alertRecordSign.getId());
                map.put("eventId", alertRecordSign.getAlertTime());
                map.put("handleDetail", alertRecordSign.getDealtRecord());
                map.put("handleType", DealtType.parse(alertRecordSign.getDealtResult()).getName());
                map.put("completed", alertRecordSign.getIsFinished() == 0 ? "未办结" : "已办结");
                map.put("handleTime", format.format(alertRecordSign.getCreatedAt()));
                maps.add(map);
            });
        }
        log.info("handle-响应：{}", JSONObject.toJSONString(maps));
        return maps;
    }


    private List<AlertLogResponse> getAlertLogResponsePageUtil(DeviceRequest request, int count
            , List<AlertLogResponse> alertLogResponses, String spId) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
        count = count + 1;
        RecordLogRequest recordLogRequest = new RecordLogRequest();
        recordLogRequest.setTimeStart(df.format(DateUtil.parse(request.getStartTime())));
        recordLogRequest.setTimeEnd(df.format(DateUtil.parse(request.getEndTime())));
        recordLogRequest.setImei(request.getImei());
        recordLogRequest.setPage(count);
        recordLogRequest.setPageSize(50);
        recordLogRequest.setSpId(spId);
        recordLogRequest.setTemplateType(1);
        PageUtil<AlertLogResponse> list = historyAlarmService.getAlarmList(recordLogRequest);
        alertLogResponses.addAll(list.getList());
        if (count >= 5) return alertLogResponses;
        if (list.getTotal() > 50) {
            getAlertLogResponsePageUtil(request, count, alertLogResponses, spId);
        }
        log.info("getAlertLogResponsePageUtil-响应：{}", JSONObject.toJSONString(alertLogResponses));
        return alertLogResponses;
    }


    public int getStatus(String deviceId, String spId, boolean res) {
        log.info("getStatus-imei:{},res:{},spId:{}", deviceId, res, spId);
        int status = 0;
        //获取这个点位
        DeviceState deviceState = deviceStateMapper.selectByDeviceId(deviceId, spId);
        if (deviceState != null) {
            status = deviceState.getDeviceStatus() == null ? 0 : deviceState.getDeviceStatus();
        }
        log.info("warnStrategy-status:{}", status);
        return status;

    }


}